<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="名称">
          <el-input
            v-model="formInline.name"
            placeholder="请输入字段名称"
            clearable
            @keyup.enter="onSubmit"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" :icon="Search"
            >搜 索</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <el-card>
      <div class="app__body__container" v-loading="loading">
        <div class="ma__b__15">
          <el-button
            type="primary"
            :icon="Plus"
            @click="openDialog({ isEdit: false })"
            >新增字段</el-button
          >
          <el-button type="danger" @click="delAll" :icon="Delete"
            >批量删除</el-button
          >
        </div>
        <div class="app__body__table__container">
          <el-table
            :data="tableData"
            stripe
            border
            style="width: 100%"
            highlight-current-row
            show-overflow-tooltip
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column label="看板显示内容">
              <template #default="scope">
                <span>{{ scope.row.label || "/" }}</span>
              </template>
            </el-table-column>
            <el-table-column label="字段类型">
              <template #default="scope">
                {{
                  scope.row.formType && formTypeMap[scope.row.formType]
                    ? formTypeMap[scope.row.formType]
                    : "其他类型"
                }}
              </template>
            </el-table-column>
            <el-table-column label="能否删除" align="center">
              <template #default="scope">
                <span>{{ scope.row.canDel == 1 ? "能删除" : "不能删除" }}</span>
              </template>
            </el-table-column>
            <el-table-column label="看板中是否显示" align="center">
              <template #default="scope">
                <span>{{ scope.row.isListShow == 1 ? "显示" : "不显示" }}</span>
              </template>
            </el-table-column>
            <el-table-column label="表单中是否显示" align="center">
              <template #default="scope">
                <span>{{ scope.row.isFormShow == 1 ? "显示" : "不显示" }}</span>
              </template>
            </el-table-column>
            <el-table-column label="app中是否显示" align="center">
              <template #default="scope">
                <span>{{ scope.row.isAppShow == 1 ? "显示" : "不显示" }}</span>
              </template>
            </el-table-column>

            <el-table-column label="选项列表">
              <template #default="scope">
                <div
                  v-if="
                    scope.row.formType == 'radio' ||
                    scope.row.formType == 'checkbox'
                  "
                >
                  <div v-if="scope.row.option && scope.row.option.length">
                    <div
                      class="option_item"
                      v-for="(item, index) in scope.row.option"
                      :key="index"
                    >
                      <span>{{ index + 1 }}、</span>
                      <span>选项说明：{{ item.label }}</span>
                      <span> ； </span>
                      <span>选项选项值：{{ item.value }}</span>
                    </div>
                  </div>
                  <div v-else>暂未添加选项内容</div>
                </div>
                <div v-else>/</div>
              </template>
            </el-table-column>
            <el-table-column label="是否必填">
              <template #default="scope">
                <span
                  v-if="
                    scope.row.rule &&
                    scope.row.rule.length &&
                    scope.row.rule[0].required
                  "
                >
                  必填
                </span>
                <span v-else>非必填</span>
              </template>
            </el-table-column>
            <el-table-column label="错误提示内容">
              <template #default="scope">
                <span v-if="scope.row.rule && scope.row.rule.length">
                  <span v-if="scope.row.rule[0].message">{{
                    scope.row.rule[0].message
                  }}</span>
                  <span v-else>{{ "暂无内容" }}</span>
                </span>
                <span v-else>/</span>
              </template>
            </el-table-column>
            <el-table-column property="addTime" label="添加时间" width="170">
            </el-table-column>
            <el-table-column property="updateTime" label="更新时间" width="170">
            </el-table-column>
            <el-table-column
              label="操作"
              fixed="right"
              width="300"
              align="center"
            >
              <template #default="scope">
                <div>
                  <el-button
                    type="success"
                    v-if="scope.$index > 0"
                    :icon="SortUp"
                    @click.stop.prevent="
                      sortFieldService(
                        scope.row.fieldId,
                        tableData[scope.$index - 1].fieldId
                      )
                    "
                    >上移</el-button
                  >
                  <el-button
                    type="primary"
                    :icon="Edit"
                    @click.stop.prevent="
                      openDialog({ isEdit: true, row: scope.row })
                    "
                    >编辑</el-button
                  >
                  <el-button
                    v-if="
                      scope.row.canDel == 1 &&
                      noDelKeyList.indexOf(scope.row.key) == -1
                    "
                    :icon="Delete"
                    type="danger"
                    @click.stop.prevent="delRow(scope.row)"
                    >删除</el-button
                  >
                  <el-button
                    type="success"
                    v-if="scope.$index < tableData.length - 1"
                    :icon="SortDown"
                    @click.stop.prevent="
                      sortFieldService(
                        scope.row.fieldId,
                        tableData[scope.$index + 1].fieldId
                      )
                    "
                    >下移</el-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div class="app__body__table__pagination">
            <pagination
              v-if="count > 0"
              v-model:total="count"
              v-model:page="pageInfo.page"
              v-model:limit="pageInfo.limit"
              @pagination="handleQuery"
            />
          </div>
        </div>
      </div>
    </el-card>
    <AddBulletinBoardDialog
      ref="AddBulletinBoardDialogRef"
      @submitSuccess="onSubmit"
    />
  </div>
</template>

<script lang="ts" setup name="BulletinBoard">
import { getOrderField, sortField, delOrderField } from "@/api/order/index";
import { type OrderFieldItem } from "@/api/order/types";
import AddBulletinBoardDialog from "./components/AddBulletinBoardDialog.vue"; // 添加自定义字段
import {
  Plus,
  Edit,
  Delete,
  Search,
  SortDown,
  SortUp,
} from "@element-plus/icons-vue";

const formInline = reactive({
  name: "",
});
const onSubmit = () => {
  pageInfo.value.page = 1;
  getOrderFieldService();
};

const pageInfo = ref<PageInfoType>({
  page: 1,
  limit: 10,
});
const loading = ref<boolean>(false);
const tableData = ref<OrderFieldItem[]>([]);
const count = ref<number>(0);
const formTypeMap = ref({
  input: "输入框",
  radio: "单选框",
  checkbox: "多选",
  number: "数字输入",
  textarea: "文本说明",
  datetime: "日期选择",
  read: "只读",
  image: "图片",
  craftState: "工艺内容",
  amount: "金额输入",
});

const handleQuery = () => {
  getOrderFieldService();
};

const getOrderFieldService = async () => {
  let params = {
    ...pageInfo.value,
    filter: JSON.stringify({ label: formInline.name, orderId: 0 }),
  };
  loading.value = true;
  let res = await getOrderField(params);
  loading.value = false;
  if (res) {
    count.value = res.data.count;
    tableData.value = [...res.data.list];
    console.log("tableData  ", tableData.value);
  }
};

// ------------表格相关操作

const noDelKeyList = [
  "password",
  "error_number",
  "not_received_money",
  "received_money",
  "order_money",
  "day",
  "craft_state",
  "product_images",
  "craft_images",
  "remark",
  "urgency",
  "order_state",
  "customer_name",
  "sell_goods_time",
  "stock_goods_time",
  "style",
  "number",
];

// 表格多选
const multipleSelection = ref<OrderFieldItem[]>([]);
const handleSelectionChange = (val: OrderFieldItem[]) => {
  console.log("当前选中  ", val);
  multipleSelection.value = val;
};

// 移动
const sortFieldService = async (fieldId: number, changeFieldId: number) => {
  let data = {
    fieldId: fieldId, // 当前id
    changeFieldId: changeFieldId, // 目标id
  };
  if (!data.fieldId || !data.changeFieldId) {
    return;
  }
  let res = await sortField(data);
  if (res && res.code === 20000) {
    ElMessage({
      message: "移动成功",
      type: "success",
    });
    pageInfo.value.page = 1;
    getOrderFieldService();
  }
};

// 删除一行
const delRow = (row: OrderFieldItem) => {
  ElMessageBox.confirm("您确定要删除该字段吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      delOrderFieldService(row.fieldId);
    })
    .catch(() => {
      ElMessage({
        message: "已取消",
        type: "info",
      });
    });
};

// 删除 多选
const delAll = () => {
  if (!multipleSelection.value.length) {
    ElMessage({
      message: "请选择需要删除的字段",
      type: "error",
    });
    return;
  }
  if (
    multipleSelection.value.filter((elm: OrderFieldItem) => elm.canDel != 1)
      .length
  ) {
    console.log(
      "-------------   multipleSelection.value.filter((elm) => elm.canDel == 1)",
      multipleSelection.value.filter((elm: OrderFieldItem) => elm.canDel != 1)
    );
    ElMessage({
      message: "不能选择无法删除的字段",
      type: "error",
    });
    return;
  }
  let ids = multipleSelection.value.map((elm: OrderFieldItem) => {
    return elm.fieldId;
  });
  ElMessageBox.confirm("您确定要删除这些字段吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      delOrderFieldService(ids.join(","));
    })
    .catch(() => {
      ElMessage({
        message: "已取消",
        type: "info",
      });
    });
};

const delOrderFieldService = async (fieId: number) => {
  let res = await delOrderField(fieId, {});
  if (res) {
    ElMessage({
      message: "删除成功",
      type: "success",
    });
    pageInfo.value.page = 1;
    getOrderFieldService();
  }
};

const AddBulletinBoardDialogRef = ref<typeof AddBulletinBoardDialog>(null);

// 编辑/新增 一行
const openDialog = (data: { isEdit: boolean; row?: OrderFieldItem }) => {
  AddBulletinBoardDialogRef.value.handleOpen(data);
};

getOrderFieldService();
</script>

<style lang="scss" scoped>
.app__body__container {
  .app__body__buttons__container {
    margin-bottom: 18px;
  }
  .app__body__table__container {
  }
}
</style>
